package com.itheima.reggie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.ConstantUtil;
import com.itheima.reggie.common.Page;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DisFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
//日志注解
public class DishServiceImpl implements DishService {

    @Autowired
    private DisFlavorMapper disFlavorMapper ;

    @Autowired
    private DishMapper dishMapper ;

    @Autowired
    private CategoryMapper categoryMapper ;

    @Autowired
    private RedisTemplate redisTemplate ;

    //新增菜品
    @Override
    @Transactional
    public void save(DishDto dishDto) {
        //给菜品添加时间
        dishDto.setUpdateTime(LocalDateTime.now());
        dishDto.setCreateTime(LocalDateTime.now());
        //获取菜品中的口味
        List<DisFlavor> flavors = dishDto.getFlavors();
        dishDto.setSort(0);
        //展示参数是什么
        Dish dish = (Dish)dishDto;
        System.out.println(dish);
        //保存菜品，但是要回显id值
        dishMapper.save(dishDto);
        if(CollUtil.isNotEmpty(flavors)) {
            for (DisFlavor flavor : flavors) {
                flavor.setCreateTime(LocalDateTime.now());
                flavor.setUpdateTime(LocalDateTime.now());
                flavor.setDishId(dishDto.getId());
                disFlavorMapper.save(flavor);
            }
        }
        //要是保存就可以知道那个分类改了，就没问题
        Set keys = redisTemplate.keys(ConstantUtil.DISH_ONSALE + dishDto.getCategoryId());

        redisTemplate.delete(keys);
    }

    @Override
    public Page<DishDto> findAllDish(Integer page, Integer pageSize, String name) {
        //首先查询出类型id与name的map关系
        List<Category> allCategory = categoryMapper.findAllByType(1);
        HashMap< Long , String > map = new HashMap<>();
        for (Category category : allCategory) {
            map.put( category.getId() , category.getName() );
        }
        PageHelper.startPage( page , pageSize );

        //然后查询所以菜品
        List<Dish> dishList  = dishMapper.findAll(name);
        PageInfo<Dish> dishPageInfo = new PageInfo<>(dishList);
        List<Dish> list = dishPageInfo.getList();

        List<DishDto> dishDtos = new ArrayList<>();
        //然后转换成DishDto格式
        for (Dish dish : list) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties( dish , dishDto );
            dishDto.setCategoryName(map.get(dish.getCategoryId()));
            dishDtos.add(dishDto);
        }

        return new Page<DishDto>( dishPageInfo.getTotal() , dishDtos );

    }

    //数据回显
    @Override
    public DishDto findById(Long id) {
       //先查看对应的菜品
       Dish dish =  dishMapper.findById(id);
       //在查看对于的口味
       List<DisFlavor> disFlavors  = disFlavorMapper.findByDishId(dish.getId());
       //创建一个DishDto对象
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties( dish , dishDto );
        dishDto.setFlavors(disFlavors);

        return dishDto;
    }

    //修改菜品
    @Override
    @Transactional
    public void update(DishDto dishDto) {

        dishDto.setUpdateTime(LocalDateTime.now());

        //先更新菜品
        dishMapper.update(dishDto);
        //在删除菜品对于的所有口味
        disFlavorMapper.deleteByDishId(dishDto);

        //获取口味集合
        List<DisFlavor> flavors = dishDto.getFlavors();

        if(CollUtil.isNotEmpty(flavors)) {
            for (DisFlavor flavor : flavors) {
                flavor.setCreateTime(LocalDateTime.now());
                flavor.setUpdateTime(LocalDateTime.now());
                flavor.setCreateUser(dishDto.getCreateUser());
                flavor.setUpdateUser(dishDto.getUpdateUser());
                flavor.setDishId(dishDto.getId());
                disFlavorMapper.save(flavor);
            }
        }

        //要是修改了就要把缓存全部删除，不知道原来的分类id是什么
        Set keys = redisTemplate.keys(ConstantUtil.DISH_ONSALE + "*");

        redisTemplate.delete(keys);

    }

    //根据分类id查看菜品，同时要能销售
    @Override
    public List<DishDto> findByCategoryId(Long categoryId ) {

        ValueOperations valueOperations = redisTemplate.opsForValue();

        List<DishDto> dishDtoList = (List<DishDto>) valueOperations.get(ConstantUtil.DISH_ONSALE + categoryId);

        if(dishDtoList != null ){
            log.info("正在redis中获取菜品，分类为" + categoryId );
            return dishDtoList ;
        }

        List<Dish> dishList = dishMapper.findAllSaleByCategoryById(categoryId);

        ArrayList<DishDto> dishDtos = new ArrayList<>();

        for (Dish dish : dishList) {

            DishDto dishDto = new DishDto();

            List<DisFlavor> byDishId = disFlavorMapper.findByDishId(dish.getId());

            BeanUtils.copyProperties( dish , dishDto );

            dishDto.setFlavors(byDishId);

            dishDtos.add(dishDto);
        }

        valueOperations.set(ConstantUtil.DISH_ONSALE + categoryId , dishDtos );

        return dishDtos ;

    }

    //修改状态码
    @Override
    public void status(Dish dish ) {
        dishMapper.status(dish);
    }

}
